package com.kotlin.android.api.base

import com.kotlin.android.api.ApiResult
import com.kotlin.android.core.BaseViewModel
import com.kotlin.android.core.CoreApp
import com.kotlin.android.ktx.ext.e
import com.kotlin.android.ktx.ext.toast

/**
 *
 * Created on 2020/4/27.
 *
 * @author o.s
 */

/**
 * 可扩展多种类型的结果处理方案
 */
fun <T : Any> BaseViewModel.checkResult(
    result: ApiResult<T>,
    error: ((message: String?) -> Unit)? = null,
    netError: ((message: String) -> Unit)? = null,
    needLogin: ((message: String?) -> Unit)? = null,
    success: ((data: T) -> Unit)? = null
) {
    result.e()
    when (result) {
        is ApiResult.Success -> {
            success?.invoke(result.data)
        }
        is ApiResult.Error -> {
            val code = result.code
            val message = result.message
            when (code) {
                ApiResult.ErrorCode.ERROR -> {
                    error?.invoke(message)
                }
                ApiResult.ErrorCode.NET_ERROR -> {
                    netError?.invoke(message.orEmpty())
                }
                ApiResult.ErrorCode.NEED_LOGIN -> {
                    // 需要跳转到登录页
                    needLogin?.invoke(message)
                }
                ApiResult.ErrorCode.RESULT_LIMIT -> {
                    error?.invoke(message)
                    toast(CoreApp.instance, message)
                }
            }
        }
    }
}